package com.omazan.db;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;

import com.omazan.db.models.ProductType;
import com.omazan.utils.OmazanException;

public class HandleProductTypes {

	public ProductType readProductTypeFromDBUsingId(int id)
			throws OmazanException {

		ProductType productType = null;
		try {
			SessionFactory sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();

			// get new session
			Session session = sessionFactory.openSession();
			session.beginTransaction();

			productType = (ProductType) session.get(ProductType.class, id);
			return productType;
		} catch (HibernateException e) {

			e.printStackTrace();
			return null;

		}

	}

	@SuppressWarnings("unchecked")
	public List<ProductType> readAllProductTypesFromDB() throws OmazanException {

		List<ProductType> listOfproductsTypes = new ArrayList<ProductType>();
		Session session = null;

		try {

			session = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation().openSession();

			Query query = session.createQuery("from ProductType")
					.setResultTransformer(
							CriteriaSpecification.DISTINCT_ROOT_ENTITY);

			listOfproductsTypes = (List<ProductType>) query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return listOfproductsTypes;
	}

	public boolean insertProductType(ProductType obj) throws OmazanException {

		try {

			SessionFactory sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();

			// get new session
			Session session = sessionFactory.openSession();
			session.beginTransaction();

			session.save(obj);
			session.getTransaction().commit();
			session.close();
			return true;

		} catch (HibernateException e) {

			e.printStackTrace();
			return false;

		}

	}
	
	public boolean deleteUsingId(int id){
		
		
		SessionFactory sessionFactory;
		try {
			sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();
			Session session = sessionFactory.openSession();  
			session.beginTransaction();  
			ProductType productType = readProductTypeFromDBUsingId(id);
			session.delete(productType);  
			session.getTransaction().commit(); 
			
		} catch (OmazanException e) {
			
			e.printStackTrace();
			return false;
		}		
		
		return true;
	}

}
